package com.discovery.darchrow.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.discovery.darchrow.net.HttpMethodType;
import com.discovery.darchrow.net.URLConnectionUtil;

/**
 * Http请求简要封装
 * 
 * @author dongliang ma
 *
 */
public class HttpSimpleUtils {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(HttpSimpleUtils.class);

	public static String service(String queryString, 
			String uri,
			String method) throws Exception {
		if(HttpMethodType.GET.name().equalsIgnoreCase(method)) {
			return URLConnectionUtil.getResponseBodyAsString(queryString);
		} else {
			return post(uri, queryString);
		}
	}
	
	public static String post(String urlStr, String xmlInfo) {  
		StringBuffer sb = new StringBuffer();
        try {  
            URL url = new URL(urlStr);  
            URLConnection con = url.openConnection();  
            con.setDoOutput(true);  
            //con.setRequestProperty("Pragma:", "no-cache");  
            con.setRequestProperty("Cache-Control", "no-cache");  
            con.setRequestProperty("Content-Type", "text/xml");  
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());      
            out.write(new String(xmlInfo.getBytes("UTF-8")));  
            out.flush();  
            out.close();  
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));  
            String line = "";
            for (line = br.readLine(); line != null; line = br.readLine()) {  
            	sb.append(line);
            }  
        } catch (MalformedURLException e) {  
        	LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {  
        	LOGGER.error(e.getMessage(), e);
        } catch (Exception e) {
        	LOGGER.error(e.getMessage(), e);
        }
        return sb.toString();
    }
	
}
